package com.jams.goodox.activity.home;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lvman.configs.instrumentation.InstrumentedDraweeView;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallBacks;
import com.jams.goodox.net.services.HomeService;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.FrescoUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.MaxListView;
import com.jams.goodox.widget.NoScrollGridView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Response;

/**
 * 购物车页面
 * Created by Administrator on 2017/10/5.
 */

public class BuyCarDialogActivity extends Activity {

    @Bind(R.id.tx_number_icon)
    TextView txNumberIcon;
    @Bind(R.id.tx_good_number)
    TextView txGoodNumber;
    @Bind(R.id.btn_parking_decrease)
    TextView btnParkingDecrease;
    @Bind(R.id.tv_parking_count)
    TextView tvParkingCount;
    @Bind(R.id.btn_parking_plus)
    TextView btnParkingPlus;
    @Bind(R.id.lv_edit_count_group)
    LinearLayout lvEditCountGroup;
    @Bind(R.id.relative_bottom)
    RelativeLayout relativeBottom;
    @Bind(R.id.linear_setting)
    LinearLayout linearSetting;
    @Bind(R.id.tx_price)
    TextView txPrice;
    @Bind(R.id.tx_choose_setting)
    TextView txChooseSetting;
    @Bind(R.id.img_clean)
    ImageView imgClean;
    @Bind(R.id.sdv_img_show)
    InstrumentedDraweeView sdvImgShow;
    @Bind(R.id.list_set)
    MaxListView list_set;
    @Bind(R.id.tx_in_buy_car)
    TextView tx_in_buy_car;

    private ListCommonAdapter listCommonAdapter;
    private List<GoodsBean.Option> optionList;

    private List<GoodsBean.Child> selectChilds;

    private String id;
    private int maxNumber=0;
    private double price=0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buy_car_dialog);
        ButterKnife.bind(this);

        Window window = getWindow();
        WindowManager.LayoutParams la = window.getAttributes();
        la.width = WindowManager.LayoutParams.MATCH_PARENT;
        la.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(la);
        id = getIntent().getStringExtra("id");
        getGoodDetail(id);
        initAdapter();
        list_set.setListViewHeight(DensityUtil.dp2px(this, 250));
        selectChilds = new ArrayList<>();
    }

    private void initAdapter() {
        optionList = new ArrayList<>();
        listCommonAdapter = new ListCommonAdapter<GoodsBean.Option>(this, optionList, R.layout.option_item) {
            @Override
            public void convert(ListCommonViewHolder helper, final GoodsBean.Option item,final int itemPosition) {
                helper.setText(R.id.tx_type, item.getTitle());
                NoScrollGridView noScrollGridView = helper.getView(R.id.grid_color);
                final SettiongAdapter colorAdapter = new SettiongAdapter(BuyCarDialogActivity.this, item.getChild());
                noScrollGridView.setAdapter(colorAdapter);
                noScrollGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        doFalseChoose(item.getChild(), position,itemPosition);
                        colorAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        list_set.setAdapter(listCommonAdapter);
    }

    private void getGoodDetail(String id) {
        ProtocolManagers.getInstance(this).getService(HomeService.class).getProductDetail(SePref.getToken(), id, "").enqueue(new RetrofitCallBacks<GoodsBean>(this) {
            @Override
            public void onSuccess(Response<GoodsBean> response) {
                if (response.body() != null && response.isSuccessful() && "0".equalsIgnoreCase(response.body().getStatus())) {
                    GoodsBean result = response.body();
                    if (result.getData() == null || result.getData().getInfo() == null || result.getData().getComment() == null)
                        return;
                    GoodsBean.Info info = result.getData().getInfo();
                    List<GoodsBean.Option> options = info.getOption();
                    optionList.clear();
                    optionList.addAll(options);
                    listCommonAdapter.notifyDataSetChanged();
                    price=StringUtils.toDouble(info.getPrice());
                    txPrice.setText(info.getPrice());
                    if (info.getMultiple() != null && info.getMultiple().size() > 0) {
                        FrescoUtils.loadUrl(BuyCarDialogActivity.this, sdvImgShow, info.getMultiple().get(0).getSrc());
                    }
                }
            }

            @Override
            public void onFail(String message) {

            }

            @Override
            public void unSuccessStatus(String status, String message) {

            }
        });
    }

    private void doFalseChoose(List<GoodsBean.Child> setList, int position,int itemPosition) {
        if (setList == null || setList.size() == 0) return;
        for (int i = 0, len = setList.size(); i < len; i++) {
            if (i == position) {//於此，重置item的選擇
                if(itemPosition==0){
                    if (StringUtils.toInt(setList.get(i).getNum()) == 0) {
                        ToastUtil.show(String.format("%s库存为0，不能加入购物车",setList.get(i).getName()));
                        return;//加上為0不能選擇邏輯
                    }
                    maxNumber = StringUtils.toInt(setList.get(i).getNum());//賦初始值
                }
                setList.get(i).setChoose(!setList.get(i).isChoose());
                if (setList.get(i).isChoose()) {//由飛+
                    selectChilds.add(setList.get(i));
                } else {
                    selectChilds.remove(setList.get(i));
                }
                txGoodNumber.setText(String.format("(当前库存%s件)", String.valueOf(maxNumber)));
            } else {
                setList.get(i).setChoose(false);
                selectChilds.remove(setList.get(i));
            }
        }
        setAllPrice();
        notifyChooseSetting();
    }

    private void setAllPrice(){
        double usePrice=price;
        if(selectChilds.size()>0){
            for(GoodsBean.Child child:selectChilds){
                if(StringUtils.toDouble(child.getPrice())>0)
                    usePrice+=StringUtils.toDouble(child.getPrice());
            }
        }
        txPrice.setText(String.valueOf(usePrice));
    }

    private int getMaxNumber() {
        int maxNumber = -1;
        for (GoodsBean.Child child : selectChilds) {
            if (maxNumber < 0) maxNumber = StringUtils.toInt(child.getNum());//賦初始值
            else {
                maxNumber = StringUtils.toInt(child.getNum()) > maxNumber ? maxNumber : StringUtils.toInt(child.getNum());
            }
        }
        return maxNumber;
    }

    private void notifyChooseSetting() {
        StringBuffer sb = new StringBuffer();
        for (GoodsBean.Child child : selectChilds) {
            sb.append(String.format("%s/%s  ", child.getTitle(), child.getName()));
        }
        txChooseSetting.setText(sb);
    }

    @OnClick(R.id.img_clean)
    public void onClick() {
        finish();
    }

    @OnClick(R.id.btn_parking_decrease)
    public void plus() {
        int count = StringUtils.toInt(tvParkingCount.getText());
        if (count > 1) {
            count--;
            tvParkingCount.setText(StringUtils.toString(count));
        }
    }

    @OnClick(R.id.btn_parking_plus)
    public void decrease() {
        int count = StringUtils.toInt(tvParkingCount.getText());
        if (count < maxNumber) {
            count++;
            tvParkingCount.setText(StringUtils.toString(count));
        }
    }

    @OnClick(R.id.tx_in_buy_car)
    public void inBuyCar() {
        String number= tvParkingCount.getText().toString();
        if(StringUtils.toInt(number)==0){
            ToastUtil.show(this,"请添加至少一个");
            return;
        }
        HashMap<String, String> param = new HashMap<>();
        param.put("token", SePref.getToken());
        param.put("id", id);
        param.put("num", tvParkingCount.getText().toString());
        for (GoodsBean.Child child : selectChilds) {
            param.put(child.getMethod(), child.getName());
        }
        ProtocolManagers.getInstance(this).getService(HomeService.class).joinShopCart(param).enqueue(new RetrofitCallBacks<BaseEntity>(this) {
            @Override
            public void onSuccess(Response<BaseEntity> response) {
                finish();
            }

            @Override
            public void onFail(String message) {

            }

            @Override
            public void unSuccessStatus(String status, String message) {

            }
        });
    }
}
